package net.torbenvoltmer.vepa.TCP;
import net.torbenvoltmer.vepa.Shared.*;
import net.torbenvoltmer.vepa.Shared.Networking.ListRequest;
import net.torbenvoltmer.vepa.Shared.Networking.ListResponse;
import net.torbenvoltmer.vepa.Shared.Networking.VepaRequest;

import java.io.*;
import java.net.*;
import com.google.gson.*;

/**
 * Created by Torben on 6/30/13.
 */


public class TCPClient {

    private Socket clientSocket;
    private DataOutputStream out;
    private BufferedReader in;
    DataInputStream inStream;
    private Gson gson;
    public TCPClient()
    {
        try {
        clientSocket = new Socket("10.0.0.1", 7879);
        out = new DataOutputStream(clientSocket.getOutputStream());
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
             inStream = new DataInputStream(clientSocket.getInputStream());

        }
        catch (UnknownHostException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        gson = new Gson();
    }

    public VepaInfo[] getList()
    {
        try {
        ListRequest request = new ListRequest();
        out.writeBytes(gson.toJson(request));

        byte[] buffer = new byte[32];
        StringBuilder stringBuilder = new StringBuilder();
        int numberOfBytes = 0;
        do {
            numberOfBytes = inStream.read(buffer,0, buffer.length);
            stringBuilder.append(new String(buffer,0,numberOfBytes));
        }while(inStream.available() > 0);

        ListResponse list = gson.fromJson(stringBuilder.toString(),ListResponse.class);
        return list.List;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }



    public VepaPDF getVepa(Integer version)
    {
        return null;
    }

    /*
    Returns the latest Vepa
     */
    public VepaPDF getVepa()
    {
        return null;
    }

}
